<template>
  <div v-if="contact" class="h-full bg-[#f5f5f7]">
    <!-- 用户基本信息卡片 -->
    <div class="p-8 bg-white/80 backdrop-blur-xl border-b border-gray-100 shadow-sm">
      <div class="max-w-md mx-auto text-center">
        <el-avatar :size="88" :src="contact.avatar" class="ring-4 ring-white shadow-lg">
          {{ contact.nickname.charAt(0) }}
        </el-avatar>
        <h2 class="mt-4 text-2xl font-medium text-gray-900">{{ contact.nickname }}</h2>
        <p class="mt-1 text-sm font-medium text-gray-500">@{{ contact.username }}</p>
        <div class="mt-3 inline-flex items-center px-3 py-1 rounded-full text-xs font-medium transition-colors" :class="{
          'bg-green-50 text-green-700 ring-1 ring-green-600/20': contact.status === 1,
          'bg-gray-50 text-gray-600 ring-1 ring-gray-500/20': contact.status === 0
        }">
          {{ contact.status === 1 ? '在线' : '离线' }}
        </div>
      </div>
    </div>

    <!-- 操作按钮组 -->
    <div class="max-w-md mx-auto px-4 -mt-4 relative z-10 flex gap-3">
      <el-button type="primary" class="flex-1 h-11 text-sm font-medium rounded-xl shadow-sm 
        bg-gradient-to-r from-blue-500 to-blue-600 border-0 hover:from-blue-600 hover:to-blue-700 
        !flex !items-center !justify-center" @click="handleStartChat">
        <template #icon>
          <el-icon class="mr-1">
            <ChatDotRound />
          </el-icon>
        </template>
        发起聊天
      </el-button>
      <el-button class="flex-1 h-11 text-sm font-medium rounded-xl shadow-sm 
        bg-gradient-to-r from-gray-50 to-gray-100 border-0 hover:from-gray-100 hover:to-gray-200
        !flex !items-center !justify-center" @click="handleVideoCall">
        <template #icon>
          <el-icon class="mr-1">
            <VideoCamera />
          </el-icon>
        </template>
        视频通话
      </el-button>
    </div>

    <!-- 用户详细信息卡片 -->
    <div class="max-w-md mx-auto mt-6 px-4">
      <div class="bg-white/80 backdrop-blur-xl rounded-2xl shadow-sm overflow-hidden">
        <h3 class="px-4 py-3 text-sm font-medium text-gray-900 border-b border-gray-100">
          详细信息
        </h3>
        <div class="divide-y divide-gray-100">
          <!-- 备注 -->
          <div class="flex items-center justify-between px-4 py-3 hover:bg-gray-50 transition-colors">
            <span class="text-sm text-gray-600">备注</span>
            <div class="flex items-center">
              <span v-if="!isEditingRemark" class="text-sm text-gray-900 mr-2">{{ contact.remark || '未设置' }}</span>
              <el-input v-else v-model="editingRemark" size="small" class="w-32" @keyup.enter="handleUpdateRemark"
                @blur="handleUpdateRemark" />
              <el-icon class="text-gray-400 cursor-pointer hover:text-gray-600 transition-colors"
                @click="handleEditRemark">
                <Edit />
              </el-icon>
            </div>
          </div>

          <!-- 添加时间 -->
          <div class="flex items-center justify-between px-4 py-3 hover:bg-gray-50 transition-colors">
            <span class="text-sm text-gray-600">添加时间</span>
            <span class="text-sm text-gray-900">{{ formatDate(contact.createdAt) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部删除按钮 -->
    <div class="max-w-md mx-auto px-4 mt-6 mb-8">
      <el-button type="danger" class="w-full h-11 text-sm font-medium rounded-xl shadow-sm
        bg-gradient-to-r from-red-500 to-red-600 border-0 hover:from-red-600 hover:to-red-700" @click="handleDelete">
        <template #icon>
          <el-icon>
            <Delete />
          </el-icon>
        </template>
        删除好友
      </el-button>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="showDeleteConfirm" title="删除好友" width="360px" center :show-close="false" class="rounded-2xl">
      <div class="text-center">
        <el-icon :size="48" class="text-red-500 mb-4">
          <Warning />
        </el-icon>
        <p class="text-gray-600">确定要删除该好友吗？删除后将无法恢复。</p>
      </div>
      <template #footer>
        <div class="flex justify-center gap-4">
          <el-button @click="showDeleteConfirm = false">取消</el-button>
          <el-button type="danger" :loading="deleting" @click="confirmDelete">
            确定删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 未选择联系人时显示的提示 -->
  <div v-else-if="loading" class="h-full flex flex-col items-center justify-center bg-[#f5f5f7]">
    <el-loading />
  </div>

  <!-- 加载失败时显示的提示 -->
  <div v-else-if="error" class="h-full flex flex-col items-center justify-center bg-[#f5f5f7] text-gray-400">
    <el-icon :size="64" class="mb-4 text-red-500">
      <Warning />
    </el-icon>
    <p class="text-lg font-medium mb-4">{{ error }}</p>
    <el-button type="primary" @click="getContactInfo(route.params.id as string)">重试</el-button>
  </div>

  <!-- 未选择联系人时显示的提示 -->
  <div v-else class="h-full flex flex-col items-center justify-center bg-[#f5f5f7] text-gray-400">
    <el-icon :size="64" class="mb-4 opacity-80">
      <UserFilled />
    </el-icon>
    <p class="text-lg font-medium">选择一个联系人查看详情</p>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ChatDotRound,
  VideoCamera,
  Edit,
  Delete,
  UserFilled,
  Warning
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import type { FriendRequestData } from '@/types'
import { ChatSessionType } from '@/types'
import { getFriendList, deleteFriend, updateRemark } from '@/api/contact'
import { createSession, getSessionByTargetId } from '@/api/session'

const route = useRoute()
const router = useRouter()
const contact = ref<FriendRequestData | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const isEditingRemark = ref(false)
const editingRemark = ref('')
const showDeleteConfirm = ref(false)
const deleting = ref(false)

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 处理发起聊天
const handleStartChat = async () => {
  if (contact.value) {
    try {
      // 1.判断会话是否存在
      const session = await getSessionByTargetId(contact.value.userId)
      console.log('判断的session', session)
      if (session.data != null) {
        router.push({
          name: 'chat',
          params: { id: session.data.id }
        })
      } else {
        // 2.创建会话
        const newSession = await createSession(contact.value.userId, ChatSessionType.PRIVATE,null)
        router.push({
          name: 'chat',
          params: { id: newSession.data.id }
        })
      }
    } catch (err: any) {
      ElMessage.error(err.message || '发起聊天失败')
    }
  }
}

// 处理视频通话
const handleVideoCall = () => {
  ElMessage.info('视频通话功能开发中...')
}

// 处理编辑备注
const handleEditRemark = () => {
  if (contact.value) {
    editingRemark.value = contact.value.remark || ''
    isEditingRemark.value = true
  }
}

// 处理更新备注
const handleUpdateRemark = async () => {
  if (!contact.value) return

  try {
    // 如果备注没有变化，直接关闭编辑状态
    if (editingRemark.value === contact.value.remark) {
      isEditingRemark.value = false
      return
    }

    // 调用更新备注API
    await updateRemark(contact.value.userId, editingRemark.value)

    // 更新本地数据
    contact.value.remark = editingRemark.value
    ElMessage.success('备注更新成功')

    // 重新获取联系人列表以保持数据同步
    await getContactInfo(contact.value.id)
  } catch (err: any) {
    ElMessage.error(err.message || '备注更新失败')
    // 恢复原来的备注
    editingRemark.value = contact.value.remark || ''
  } finally {
    isEditingRemark.value = false
  }
}

// 处理删除好友
const handleDelete = () => {
  showDeleteConfirm.value = true
}

// 确认删除好友
const confirmDelete = async () => {
  if (!contact.value) return

  deleting.value = true
  try {
    await deleteFriend(contact.value.userId)
    ElMessage.success('好友删除成功')
    router.push({ name: 'contacts' })
  } catch (err: any) {
    ElMessage.error(err.message || '删除失败')
  } finally {
    deleting.value = false
    showDeleteConfirm.value = false
  }
}

// 获取联系人信息
const getContactInfo = async (id: string | number | string[]) => {
  if (Array.isArray(id)) {
    return
  }

  loading.value = true
  error.value = null
  try {
    const response = await getFriendList()
    const friend = response.data.find(item => item.id.toString() === id.toString())
    if (friend) {
      contact.value = friend
    } else {
      error.value = '未找到该联系人'
    }
  } catch (err: any) {
    error.value = err.message || '获取联系人信息失败'
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    getContactInfo(newId)
  }
}, { immediate: true })

// 组件挂载时获取联系人信息
onMounted(() => {
  if (route.params.id) {
    getContactInfo(route.params.id)
  }
})
</script>

<style scoped>
:deep(.el-button) {
  transition: all 0.3s ease;
}

:deep(.el-button .el-icon) {
  font-size: 16px;
}

:deep(.el-dialog) {
  border-radius: 1rem;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding-top: 1.5rem;
}

:deep(.el-dialog__body) {
  padding: 1.5rem;
}

:deep(.el-dialog__footer) {
  padding-bottom: 1.5rem;
}
</style>